package iot;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import iot.jtt808.FrameDecoder;
import netty.builder.NettyServerBuilder;
import netty.session.SessionManager;

import java.util.concurrent.TimeUnit;

/**
 * Created by dave on 18-7-20 下午11:12.
 */
public class TcpServer {
    private int port;
    private SessionManager sessionManager;
    private MessageProcessor messageProcessor;

    public TcpServer(int port, SessionManager sm, MessageProcessor mp) {
        this.port = port;
        this.sessionManager = sm;
        this.messageProcessor = mp;
    }

    public ChannelFuture start() {
        NettyServerBuilder builder = new NettyServerBuilder();
        builder.channelInitializer(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new IdleStateHandler(10, 0, 0, TimeUnit.MINUTES));
                ch.pipeline().addLast(new FrameDecoder());
                ch.pipeline().addLast(new JTT808Handler(sessionManager, messageProcessor));
            }
        });
        return builder.buildAndBindAsync(port);
    }
}
